from fastapi import APIRouter, HTTPException, Query
from fastapi.responses import HTMLResponse
from pydantic import BaseModel
from typing import List, Optional
import os
from .mdmanage import (
    get_zip_objects, 
    get_zip_object_by_id, 
    get_all_files, 
    read_md_file_content,
    unzip_file
)

router = APIRouter()

# 数据模型
class ZipInfo(BaseModel):
    id: int
    zip_name: str
    zip_file: str
    extract_path: str
    md_files: List[str]
    file_count: int
    status: str
    created_time: Optional[str] = None
    modified_time: Optional[str] = None
    created_timestamp: Optional[float] = None
    file_size: Optional[int] = None

class FileInfo(BaseModel):
    name: str
    path: str
    type: str
    size: int
    created_time: Optional[str] = None
    modified_time: Optional[str] = None
    created_timestamp: Optional[float] = None
    modified_timestamp: Optional[float] = None

class FileContent(BaseModel):
    filename: str
    content: str
    file_type: str

# API 路由
@router.get("/zip/list", response_model=List[ZipInfo])
async def get_zip_list():
    """获取所有ZIP包信息"""
    try:
        zip_objects = get_zip_objects()
        return zip_objects
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取ZIP列表失败: {str(e)}")

@router.get("/zip/{zip_id}/files", response_model=List[FileInfo])
async def get_zip_files(zip_id: int):
    """获取指定ZIP包的文件列表"""
    try:
        zip_obj = get_zip_object_by_id(zip_id)
        if not zip_obj:
            raise HTTPException(status_code=404, detail="ZIP包不存在")
        
        files = get_all_files(zip_obj['extract_path'])
        return files
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取文件列表失败: {str(e)}")

@router.get("/file/content", response_model=FileContent)
async def get_file_content(file_path: str = Query(..., description="文件路径")):
    """获取文件内容"""
    try:
        if not os.path.exists(file_path):
            raise HTTPException(status_code=404, detail="文件不存在")
        
        filename = os.path.basename(file_path)
        file_type = filename.split('.')[-1] if '.' in filename else 'unknown'
        
        # 读取文件内容
        try:
            content = read_md_file_content(file_path)
        except UnicodeDecodeError:
            # 如果不是文本文件，返回错误
            raise HTTPException(status_code=400, detail="无法读取非文本文件")
        
        return FileContent(
            filename=filename,
            content=content,
            file_type=file_type
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"读取文件失败: {str(e)}")

@router.post("/zip/{zip_id}/reprocess")
async def reprocess_zip(zip_id: int):
    """重新处理ZIP包"""
    try:
        zip_obj = get_zip_object_by_id(zip_id)
        if not zip_obj:
            raise HTTPException(status_code=404, detail="ZIP包不存在")
        
        # 重新解压
        success = unzip_file(zip_obj['zip_file'], zip_obj['extract_path'])
        
        if success:
            return {"message": "重新处理成功", "status": "success"}
        else:
            return {"message": "重新处理失败", "status": "failed"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"重新处理失败: {str(e)}")

@router.get("/test", response_class=HTMLResponse)
async def zip_manager_page():
    """ZIP管理页面"""
    html_content = """
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>ZIP文件管理系统</title>
        <style>
            /* Bootstrap 核心样式 - 内联版本 */
            * { box-sizing: border-box; }
            body { 
                margin: 0; 
                font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;
                font-size: 1rem; 
                font-weight: 400; 
                line-height: 1.5; 
                color: #212529; 
                background-color: #fff;
                height: 100vh;
                overflow: hidden;
            }
            .container-fluid { width: 100%; padding-right: 15px; padding-left: 15px; margin-right: auto; margin-left: auto; }
            .row { display: flex; flex-wrap: wrap; margin-right: -15px; margin-left: -15px; height: 100vh; }
            .col-md-4 { flex: 0 0 33.333333%; max-width: 33.333333%; padding-right: 15px; padding-left: 15px; }
            .col-md-8 { flex: 0 0 66.666667%; max-width: 66.666667%; padding-right: 15px; padding-left: 15px; }
            .h-100 { height: 100%!important; }
            .d-flex { display: flex!important; }
            .flex-column { flex-direction: column!important; }
            .overflow-auto { overflow: auto!important; }
            .border-end { border-right: 1px solid #dee2e6!important; }
            .p-3 { padding: 1rem!important; }
            .p-2 { padding: 0.5rem!important; }
            .mb-3 { margin-bottom: 1rem!important; }
            .mb-2 { margin-bottom: 0.5rem!important; }
            .me-2 { margin-right: 0.5rem!important; }
            .text-muted { color: #6c757d!important; }
            .small { font-size: 0.875em; }
            .btn { 
                display: inline-block; 
                font-weight: 400; 
                line-height: 1.5; 
                color: #212529; 
                text-align: center; 
                text-decoration: none; 
                vertical-align: middle; 
                cursor: pointer; 
                user-select: none; 
                background-color: transparent; 
                border: 1px solid transparent; 
                padding: 0.375rem 0.75rem; 
                font-size: 1rem; 
                border-radius: 0.25rem;
            }
            .btn-primary { color: #fff; background-color: #007bff; border-color: #007bff; }
            .btn-secondary { color: #fff; background-color: #6c757d; border-color: #6c757d; }
            .btn-outline-primary { color: #007bff; border-color: #007bff; }
            .btn-outline-primary:hover { color: #fff; background-color: #007bff; border-color: #007bff; }
            .btn-sm { padding: 0.25rem 0.5rem; font-size: 0.875rem; border-radius: 0.2rem; }
            .list-group { display: flex; flex-direction: column; padding-left: 0; margin-bottom: 0; border-radius: 0.25rem; }
            .list-group-item { 
                position: relative; 
                display: block; 
                padding: 0.75rem 1.25rem; 
                background-color: #fff; 
                border: 1px solid rgba(0,0,0,.125);
                border-top-width: 0;
            }
            .list-group-item:first-child { border-top-width: 1px; border-top-left-radius: inherit; border-top-right-radius: inherit; }
            .list-group-item:last-child { border-bottom-right-radius: inherit; border-bottom-left-radius: inherit; }
            .list-group-item.active { z-index: 2; color: #fff; background-color: #007bff; border-color: #007bff; }
            .list-group-item:hover { background-color: #f8f9fa; cursor: pointer; }
            .card { 
                position: relative; 
                display: flex; 
                flex-direction: column; 
                min-width: 0; 
                word-wrap: break-word; 
                background-color: #fff; 
                background-clip: border-box; 
                border: 1px solid rgba(0,0,0,.125); 
                border-radius: 0.25rem;
            }
            .card-header { 
                padding: 0.75rem 1.25rem; 
                margin-bottom: 0; 
                background-color: rgba(0,0,0,.03); 
                border-bottom: 1px solid rgba(0,0,0,.125);
            }
            .card-body { flex: 1 1 auto; padding: 1.25rem; overflow: auto; }
            .modal { 
                position: fixed; 
                top: 0; 
                left: 0; 
                z-index: 1055; 
                display: none; 
                width: 100%; 
                height: 100%; 
                overflow-x: hidden; 
                overflow-y: auto; 
                outline: 0;
                background-color: rgba(0,0,0,0.5);
            }
            .modal-dialog { 
                position: relative; 
                width: auto; 
                margin: 1.75rem; 
                pointer-events: none;
                max-width: 90%;
            }
            .modal-content { 
                position: relative; 
                display: flex; 
                flex-direction: column; 
                width: 100%; 
                pointer-events: auto; 
                background-color: #fff; 
                background-clip: padding-box; 
                border: 1px solid rgba(0,0,0,.2); 
                border-radius: 0.3rem;
            }
            .modal-header { 
                display: flex; 
                align-items: flex-start; 
                justify-content: space-between; 
                padding: 1rem 1rem; 
                border-bottom: 1px solid #dee2e6; 
                border-top-left-radius: calc(0.3rem - 1px); 
                border-top-right-radius: calc(0.3rem - 1px);
            }
            .modal-body { position: relative; flex: 1 1 auto; padding: 1rem; }
            .modal-footer { 
                display: flex; 
                flex-wrap: wrap; 
                align-items: center; 
                justify-content: flex-end; 
                padding: 0.75rem; 
                border-top: 1px solid #dee2e6; 
                border-bottom-right-radius: calc(0.3rem - 1px); 
                border-bottom-left-radius: calc(0.3rem - 1px);
            }
            .close { 
                float: right; 
                font-size: 1.5rem; 
                font-weight: 700; 
                line-height: 1; 
                color: #000; 
                text-shadow: 0 1px 0 #fff; 
                opacity: .5;
                background: transparent; 
                border: 0;
            }
            .close:hover { color: #000; text-decoration: none; opacity: .75; }
            h1 { font-size: 2.5rem; margin-bottom: 0.5rem; }
            h3 { font-size: 1.75rem; margin-bottom: 0.5rem; }
            h4 { font-size: 1.5rem; margin-bottom: 0.5rem; }
            h5 { font-size: 1.25rem; margin-bottom: 0.5rem; }
            pre { 
                display: block; 
                font-size: 87.5%; 
                color: #212529;
                font-family: SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;
                margin-top: 0;
                margin-bottom: 1rem;
                overflow: auto;
                background-color: #f8f9fa;
                padding: 1rem;
                border-radius: 0.25rem;
                white-space: pre-wrap;
                word-wrap: break-word;
            }
            code { 
                font-size: 87.5%; 
                color: #e83e8c; 
                word-wrap: break-word;
                font-family: SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;
            }
            pre code { color: inherit; }
            .file-icon { margin-right: 8px; }
            
            /* 补充缺失的样式 */
            .zip-list-container { height: 100%; overflow-y: auto; }
            .file-list { height: 100%; overflow-y: auto; }
            .content-viewer { 
                height: 100%; 
                overflow-y: auto; 
                padding: 1rem; 
                background-color: #fff; 
                border: 1px solid #dee2e6; 
                border-radius: 0.25rem;
            }
            .column-header { 
                background-color: #f8f9fa; 
                border-bottom: 1px solid #dee2e6; 
                padding: 1rem; 
                font-weight: bold;
                min-height: 160px;
                display: flex;
                flex-direction: column;
                justify-content: space-between;
            }
            .column-content { 
                flex: 1; 
                overflow: hidden; 
                padding: 1rem;
            }
            .main-column { 
                display: flex; 
                flex-direction: column; 
                height: 100vh;
            }
            .justify-content-between { justify-content: space-between!important; }
            .align-items-center { align-items: center!important; }
            .text-success { color: #28a745!important; }
            .text-warning { color: #ffc107!important; }
            .text-danger { color: #dc3545!important; }
            .img-fluid { max-width: 100%; height: auto; }
            .badge-secondary { background-color: #6c757d; }
            .badge-primary { background-color: #007bff; }
            .badge-success { background-color: #28a745; }
            .badge-warning { background-color: #ffc107; color: #212529; }
            .badge-danger { background-color: #dc3545; }
            .fade { transition: opacity 0.15s linear; }
            .show { opacity: 1; }
            .btn:hover { 
                filter: brightness(0.9); 
                text-decoration: none; 
            }
            .btn:focus { 
                outline: 0; 
                box-shadow: 0 0 0 0.2rem rgba(0,123,255,.25);
            }
            .list-group-item:hover { 
                background-color: #f8f9fa; 
                cursor: pointer; 
                transition: background-color 0.15s ease-in-out;
            }
            .modal.show { display: block; }
            .modal-dialog-centered { 
                display: flex; 
                align-items: center; 
                min-height: calc(100% - 1rem);
            }
            .modal-xl { max-width: 1140px; }
            @media (max-width: 768px) {
                .col-md-4 { flex: 0 0 100%; max-width: 100%; }
                .main-column { height: auto; min-height: 50vh; }
                .modal-dialog { margin: 0.5rem; }
            }
            
            /* 额外的工具类样式 */
            .ms-auto { margin-left: auto!important; }
            .me-auto { margin-right: auto!important; }
            .btn-close { 
                background: transparent url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='%23000'%3e%3cpath d='m.235.867 8.965 8.965a.25.25 0 0 0 .354 0l8.965-8.965a.25.25 0 0 0-.354-.354L8.5 9.879.835.513a.25.25 0 0 0-.354.354z'/%3e%3c/svg%3e") center/1em auto no-repeat;
                border: 0;
                border-radius: 0.25rem;
                opacity: 0.5;
                width: 1em;
                height: 1em;
                cursor: pointer;
            }
            .btn-close:hover { opacity: 0.75; }
            .position-relative { position: relative!important; }
            .position-absolute { position: absolute!important; }
            .top-0 { top: 0!important; }
            .end-0 { right: 0!important; }
            .z-1 { z-index: 1!important; }
            .bg-white { background-color: #fff!important; }
            .border { border: 1px solid #dee2e6!important; }
            .shadow-sm { box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075)!important; }
            .rounded-2 { border-radius: 0.375rem!important; }
            .fw-bold { font-weight: 700!important; }
            .text-nowrap { white-space: nowrap!important; }
            .overflow-hidden { overflow: hidden!important; }
            .text-truncate { 
                overflow: hidden!important; 
                text-overflow: ellipsis!important; 
                white-space: nowrap!important;
            }
            .md-icon { color: #0969da; }
            .txt-icon { color: #656d76; }
            .unknown-icon { color: #8b949e; }
            
            .zip-card {
                transition: transform 0.2s;
                cursor: pointer;
            }
            .zip-card:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            }
            
            .content-viewer {
                height: calc(100vh - 150px);
                min-height: 600px;
                overflow-y: auto;
                background: #f8f9fa;
                border: 1px solid #dee2e6;
                border-radius: 8px;
                padding: 20px;
            }
            
            .file-list {
                height: calc(100vh - 150px);
                min-height: 600px;
                overflow-y: auto;
                border: 1px solid #dee2e6;
                border-radius: 8px;
                padding: 15px;
                background: white;
            }
            
            .zip-list-container {
                height: calc(100vh - 100px);
                min-height: 650px;
                overflow-y: auto;
            }
            
            .file-item {
                transition: background-color 0.2s;
                padding: 12px;
                border-radius: 6px;
            }
            
            .file-item:hover {
                background-color: #f8f9fa;
            }
            
            .file-header {
                border-left: 4px solid #0d6efd;
            }
            
            .status-success { color: #198754; }
            .status-failed { color: #dc3545; }
            
            /* 确保容器占满屏幕高度 */
            .container-fluid {
                min-height: 100vh;
            }
            
            /* 调整主要列的高度 */
            .main-column {
                height: 100vh;
                display: flex;
                flex-direction: column;
            }
            
            .column-header {
                flex-shrink: 0;
                margin-bottom: 15px;
                min-height: 160px;
                display: flex;
                flex-direction: column;
                justify-content: space-between;
            }
            
            .column-content {
                flex: 1;
                overflow: hidden;
            }
            
            /* 响应式设计 */
            @media (max-width: 768px) {
                .main-column {
                    height: auto;
                    min-height: 400px;
                    margin-bottom: 20px;
                }
                
                .content-viewer, .file-list, .zip-list-container {
                    height: 400px;
                    min-height: 400px;
                }
            }
            
            /* 优化滚动条样式 */
            .content-viewer::-webkit-scrollbar,
            .file-list::-webkit-scrollbar,
            .zip-list-container::-webkit-scrollbar {
                width: 8px;
            }
            
            .content-viewer::-webkit-scrollbar-track,
            .file-list::-webkit-scrollbar-track,
            .zip-list-container::-webkit-scrollbar-track {
                background: #f1f1f1;
                border-radius: 4px;
            }
            
            .content-viewer::-webkit-scrollbar-thumb,
            .file-list::-webkit-scrollbar-thumb,
            .zip-list-container::-webkit-scrollbar-thumb {
                background: #c1c1c1;
                border-radius: 4px;
            }
            
            .content-viewer::-webkit-scrollbar-thumb:hover,
            .file-list::-webkit-scrollbar-thumb:hover,
            .zip-list-container::-webkit-scrollbar-thumb:hover {
                background: #a8a8a8;
            }
            
            /* 文本内容自动换行样式 */
            .file-content pre {
                white-space: pre-wrap !important;    /* 保留换行符并自动换行 */
                word-wrap: break-word !important;    /* 长单词强制换行 */
                word-break: break-all;               /* 在任意字符间换行 */
                overflow-wrap: break-word;           /* 现代浏览器换行方式 */
                max-width: 100%;                     /* 限制最大宽度 */
                font-family: 'Consolas', 'Monaco', 'Courier New', monospace; /* 等宽字体 */
                font-size: 14px;                     /* 合适的字体大小 */
                line-height: 1.5;                   /* 行高便于阅读 */
                background-color: #f8f9fa;          /* 浅色背景 */
                border: 1px solid #e9ecef;          /* 边框 */
                border-radius: 6px;                 /* 圆角 */
                padding: 16px;                      /* 内边距 */
                margin: 0;                          /* 移除默认边距 */
                overflow-x: auto;                   /* 水平滚动条（备用） */
            }
            
            .file-content pre code {
                white-space: pre-wrap !important;    /* 代码块也支持换行 */
                word-wrap: break-word !important;
                word-break: break-all;
                display: block;                      /* 块级显示 */
                padding: 0;                         /* 移除额外的内边距 */
                background: transparent;            /* 透明背景 */
                border: none;                       /* 移除边框 */
                font-size: inherit;                /* 继承字体大小 */
                line-height: inherit;              /* 继承行高 */
            }
            
            /* 针对hljs高亮代码的优化 */
            .file-content .hljs {
                background: #f8f9fa !important;
                overflow-x: auto;
                white-space: pre-wrap !important;
                word-wrap: break-word !important;
                word-break: break-all;
            }
            
            /* Markdown 内容换行 */
            .file-content {
                word-wrap: break-word;
                word-break: break-word;
                overflow-wrap: break-word;
                max-width: 100%;
            }
            
            /* 表格响应式 */
            .file-content table {
                word-wrap: break-word;
                word-break: break-all;
                table-layout: fixed;
                width: 100%;
            }
            
            .file-content td, .file-content th {
                word-wrap: break-word;
                word-break: break-all;
                overflow-wrap: break-word;
            }
            
            /* 长链接和代码内联元素换行 */
            .file-content code {
                white-space: pre-wrap;
                word-wrap: break-word;
                word-break: break-all;
            }
            
            .file-content a {
                word-wrap: break-word;
                word-break: break-all;
                overflow-wrap: break-word;
            
            /* 上传功能样式 */
            .upload-section {
                margin-bottom: 20px;
                padding: 15px;
                background: #f8f9fa;
                border-radius: 8px;
                border: 2px dashed #dee2e6;
                transition: all 0.3s ease;
            }
            .upload-section:hover {
                border-color: #007bff;
                background: #e3f2fd;
            }
            .upload-section.drag-over {
                border-color: #28a745;
                background: #d4edda;
            }
            .upload-input {
                display: none;
            }
            .upload-progress {
                margin-top: 10px;
                display: none;
            }
            .upload-progress .progress {
                height: 20px;
            }
            .upload-result {
                margin-top: 10px;
                display: none;
            }
            .file-size {
                font-size: 0.8em;
                color: #6c757d;
            }
            .me-2 {
                margin-right: 0.5rem;
            }
            
            }
        </style>
    </head>
    <body>
        <div class="container-fluid py-4">
            <div class="row h-100">
                <!-- 左侧：ZIP包列表 -->
                <div class="col-md-4 main-column">
                    <div class="column-header">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h3>📦 ZIP包管理</h3>
                            <button class="btn btn-primary btn-sm" onclick="refreshZipList()">
                                � 刷新
                            </button>
                        </div>
                        
                        <!-- 上传ZIP文件区域 -->
                        <div class="upload-section" id="uploadSection">
                            <div class="text-center mb-3">
                                <input type="file" id="zipFileInput" class="upload-input" accept=".zip" onchange="handleFileSelect(event)">
                                <button class="btn btn-outline-primary" onclick="document.getElementById('zipFileInput').click()">
                                    � 选择ZIP文件
                                </button>
                                <div class="small text-muted mt-2">
                                    支持拖拽文件到此区域
                                </div>
                            </div>
                            
                            <!-- 文件信息显示 -->
                            <div class="file-info" id="fileInfo" style="display: none;">
                                <div class="alert alert-info">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <strong>📎 已选择文件：</strong><span id="fileName"></span><br>
                                            <small>📏 文件大小：<span id="fileSize"></span></small>
                                        </div>
                                        <div>
                                            <button class="btn btn-success btn-sm me-2" onclick="startUpload()">
                                                🚀 开始上传
                                            </button>
                                            <button class="btn btn-outline-secondary btn-sm" onclick="cancelUpload()">
                                                ✖ 取消
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- 上传进度 -->
                            <div class="upload-progress" id="uploadProgress" style="display: none;">
                                <div class="progress">
                                    <div class="progress-bar progress-bar-striped progress-bar-animated" 
                                         id="progressBar" role="progressbar" style="width: 0%"></div>
                                </div>
                                <div class="text-center mt-2">
                                    <small id="progressText">准备上传...</small>
                                </div>
                            </div>
                            
                            <!-- 上传结果 -->
                            <div class="upload-result" id="uploadResult" style="display: none;"></div>
                        </div>
                    </div>
                    <div class="column-content">
                        <div id="zipList" class="zip-list-container"></div>
                    </div>
                </div>
                
                <!-- 中间：文件列表 -->
                <div class="col-md-4 main-column">
                    <div class="column-header">
                        <h4>📁 文件列表</h4>
                    </div>
                    <div class="column-content">
                        <div id="fileList" class="file-list">
                            <p class="text-muted text-center mt-5">请选择一个ZIP包查看文件</p>
                        </div>
                    </div>
                </div>
                
                <!-- 右侧：内容查看器 -->
                <div class="col-md-4 main-column">
                    <div class="column-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <h4>📄 内容查看器</h4>
                            <button class="btn btn-outline-secondary btn-sm" onclick="clearViewer()">
                                ✖ 清空
                            </button>
                        </div>
                    </div>
                    <div class="column-content">
                        <div id="contentViewer" class="content-viewer">
                            <p class="text-muted text-center mt-5">请选择一个文件查看内容</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 图片放大查看模态框 -->
        <div class="modal fade" id="imageModal" tabindex="-1" aria-labelledby="imageModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-xl modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="imageModalLabel">🖼️ 图片查看</h5>
                        <button type="button" class="close" onclick="hideModal('imageModal')" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body text-center">
                        <img id="modalImage" src="" alt="" class="img-fluid" style="max-width: 100%; max-height: 80vh;">
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" onclick="hideModal('imageModal')">关闭</button>
                        <button type="button" class="btn btn-primary" onclick="downloadImage()">📥 下载图片</button>
                    </div>
                </div>
            </div>
        </div>

        <script>
            // ========== 全局变量和函数定义 ==========
            
            // 全局变量
            let selectedFile = null;
            let currentZipId = null;
            
            // 文件选择处理 - 必须在页面加载前定义
            function handleFileSelect(event) {
                console.log('文件选择事件触发');
                const file = event.target.files[0];
                console.log('选择的文件:', file);
                
                if (file) {
                    selectedFile = file;
                    showFileInfo(file);
                } else {
                    console.log('没有选择文件');
                    hideFileInfo();
                }
            }
            
            // 显示文件信息
            function showFileInfo(file) {
                console.log('显示文件信息:', file.name);
                
                // 验证文件类型
                if (!file.name.toLowerCase().endsWith('.zip')) {
                    showUploadResult('error', '❌ 请选择ZIP文件');
                    hideFileInfo();
                    return;
                }
                
                // 检查文件大小
                if (file.size > 50 * 1024 * 1024) {
                    showUploadResult('error', '❌ 文件太大，请选择小于50MB的ZIP文件');
                    hideFileInfo();
                    return;
                }
                
                document.getElementById('fileName').textContent = file.name;
                document.getElementById('fileSize').textContent = formatFileSize(file.size);
                document.getElementById('fileInfo').style.display = 'block';
                
                // 隐藏之前的结果
                document.getElementById('uploadResult').style.display = 'none';
            }
            
            // 隐藏文件信息
            function hideFileInfo() {
                document.getElementById('fileInfo').style.display = 'none';
                selectedFile = null;
            }
            
            // 开始上传
            function startUpload() {
                console.log('开始上传按钮被点击');
                if (selectedFile) {
                    console.log('上传文件:', selectedFile.name);
                    hideFileInfo(); // 隐藏文件选择区域
                    uploadFile(selectedFile);
                } else {
                    console.error('没有选择文件');
                    showUploadResult('error', '❌ 请先选择文件');
                }
            }
            
            // 取消上传
            function cancelUpload() {
                console.log('取消上传');
                hideFileInfo();
                document.getElementById('zipFileInput').value = '';
                document.getElementById('uploadResult').style.display = 'none';
            }
            
            // 文件上传功能
            async function uploadFile(file) {
                console.log('开始上传文件:', file.name, '大小:', file.size);
                
                // 显示上传进度
                showUploadProgress(true);
                
                const formData = new FormData();
                formData.append('file', file);
                
                try {
                    // 使用XMLHttpRequest来跟踪上传进度
                    const xhr = new XMLHttpRequest();
                    
                    xhr.upload.addEventListener('progress', function(e) {
                        if (e.lengthComputable) {
                            const percentComplete = (e.loaded / e.total) * 100;
                            updateProgress(percentComplete);
                            console.log('上传进度:', percentComplete + '%');
                        }
                    });
                    
                    xhr.addEventListener('load', function() {
                        console.log('上传完成，状态码:', xhr.status);
                        console.log('响应内容:', xhr.responseText);
                        
                        if (xhr.status === 200) {
                            try {
                                const response = JSON.parse(xhr.responseText);
                                console.log('上传成功响应:', response);
                                // 修正字段访问路径
                                const filename = response.data ? response.data.filename : response.filename;
                                const fileSize = response.data ? response.data.file_size : response.size;
                                showUploadResult('success', `✅ 上传成功！文件：${filename}，大小：${formatFileSize(fileSize)}`);
                                // 自动刷新ZIP列表
                                setTimeout(() => {
                                    refreshZipList();
                                    resetUploadForm();
                                }, 2000);
                            } catch (parseError) {
                                console.error('解析响应失败:', parseError);
                                showUploadResult('error', '❌ 服务器响应格式错误');
                            }
                        } else {
                            try {
                                const error = JSON.parse(xhr.responseText);
                                showUploadResult('error', `❌ 上传失败：${error.detail || xhr.statusText}`);
                            } catch (parseError) {
                                showUploadResult('error', `❌ 上传失败：HTTP ${xhr.status} ${xhr.statusText}`);
                            }
                        }
                        showUploadProgress(false);
                    });
                    
                    xhr.addEventListener('error', function() {
                        console.error('网络错误');
                        showUploadResult('error', '❌ 网络错误，上传失败');
                        showUploadProgress(false);
                    });
                    
                    xhr.addEventListener('timeout', function() {
                        console.error('上传超时');
                        showUploadResult('error', '❌ 上传超时，请重试');
                        showUploadProgress(false);
                    });
                    
                    xhr.timeout = 60000; // 设置60秒超时
                    xhr.open('POST', '/api/documents/upload');
                    console.log('开始发送请求到:', '/api/documents/upload');
                    xhr.send(formData);
                    
                } catch (error) {
                    console.error('上传错误:', error);
                    showUploadResult('error', '❌ 上传过程中发生错误: ' + error.message);
                    showUploadProgress(false);
                }
            }
            
            // 显示/隐藏上传进度
            function showUploadProgress(show) {
                const progressElement = document.getElementById('uploadProgress');
                if (show) {
                    progressElement.style.display = 'block';
                    updateProgress(0);
                } else {
                    progressElement.style.display = 'none';
                }
            }
            
            // 更新上传进度
            function updateProgress(percent) {
                const progressBar = document.getElementById('progressBar');
                const progressText = document.getElementById('progressText');
                
                progressBar.style.width = percent + '%';
                progressText.textContent = `上传中... ${Math.round(percent)}%`;
                
                if (percent >= 100) {
                    progressText.textContent = '处理中...';
                }
            }
            
            // 显示上传结果
            function showUploadResult(type, message) {
                console.log('显示上传结果:', type, message);
                const resultElement = document.getElementById('uploadResult');
                if (!resultElement) {
                    console.error('找不到uploadResult元素');
                    return;
                }
                
                const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
                
                resultElement.innerHTML = `<div class="alert ${alertClass} alert-dismissible fade show">
                    ${message}
                    <button type="button" class="close" onclick="this.parentElement.style.display='none'">
                        <span>&times;</span>
                    </button>
                </div>`;
                resultElement.style.display = 'block';
                
                // 自动隐藏成功消息
                if (type === 'success') {
                    setTimeout(() => {
                        if (resultElement) {
                            resultElement.style.display = 'none';
                        }
                    }, 5000);
                }
            }
            
            // 重置上传表单
            function resetUploadForm() {
                document.getElementById('zipFileInput').value = '';
                document.getElementById('uploadResult').style.display = 'none';
                hideFileInfo();
                showUploadProgress(false);
                selectedFile = null;
            }
            
            // 格式化文件大小
            function formatFileSize(bytes) {
                if (bytes === 0) return '0 B';
                const k = 1024;
                const sizes = ['B', 'KB', 'MB', 'GB'];
                const i = Math.floor(Math.log(bytes) / Math.log(k));
                return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
            }
            
            // 拖拽上传功能
            document.addEventListener('DOMContentLoaded', function() {
                console.log('页面加载完成，初始化上传功能');
                
                // 检查必要的元素是否存在
                const uploadSection = document.getElementById('uploadSection');
                const zipFileInput = document.getElementById('zipFileInput');
                const uploadProgress = document.getElementById('uploadProgress');
                const uploadResult = document.getElementById('uploadResult');
                
                console.log('元素检查:');
                console.log('uploadSection:', uploadSection ? '✓' : '✗');
                console.log('zipFileInput:', zipFileInput ? '✓' : '✗');
                console.log('uploadProgress:', uploadProgress ? '✓' : '✗');
                console.log('uploadResult:', uploadResult ? '✓' : '✗');
                
                if (!uploadSection) {
                    console.error('找不到uploadSection元素');
                    return;
                }
                
                // 阻止默认拖拽行为
                ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
                    uploadSection.addEventListener(eventName, preventDefaults, false);
                    document.body.addEventListener(eventName, preventDefaults, false);
                });
                
                // 高亮拖拽区域
                ['dragenter', 'dragover'].forEach(eventName => {
                    uploadSection.addEventListener(eventName, highlight, false);
                });
                
                ['dragleave', 'drop'].forEach(eventName => {
                    uploadSection.addEventListener(eventName, unhighlight, false);
                });
                
                // 处理文件拖拽
                uploadSection.addEventListener('drop', handleDrop, false);
                
                function preventDefaults(e) {
                    e.preventDefault();
                    e.stopPropagation();
                }
                
                function highlight(e) {
                    uploadSection.classList.add('drag-over');
                }
                
                function unhighlight(e) {
                    uploadSection.classList.remove('drag-over');
                }
                
                function handleDrop(e) {
                    const dt = e.dataTransfer;
                    const files = dt.files;
                    
                    if (files.length > 0) {
                        const file = files[0];
                        uploadFile(file);
                    }
                }
            });
            
            // ========== 原有功能 ==========
            
            // 简化的Markdown解析器
            function parseMarkdown(text) {
                if (!text) return '';
                
                return text
                    // 标题
                    .replace(/^### (.*$)/gim, '<h3>$1</h3>')
                    .replace(/^## (.*$)/gim, '<h2>$1</h2>')
                    .replace(/^# (.*$)/gim, '<h1>$1</h1>')
                    // 粗体
                    .replace(/\*\*(.*)\*\*/gim, '<strong>$1</strong>')
                    .replace(/__(.*?)__/gim, '<strong>$1</strong>')
                    // 斜体
                    .replace(/\*(.*)\*/gim, '<em>$1</em>')
                    .replace(/_(.*?)_/gim, '<em>$1</em>')
                    // 代码块
                    .replace(/```([\s\S]*?)```/gim, '<pre><code>$1</code></pre>')
                    // 行内代码
                    .replace(/`([^`]*)`/gim, '<code>$1</code>')
                    // 链接
                    .replace(/\[([^\]]*)\]\(([^\)]*)\)/gim, '<a href="$2" target="_blank">$1</a>')
                    // 换行
                    .replace(/\n/gim, '<br>');
            }
            
            // 简化的模态框功能
            function showModal(modalId) {
                const modal = document.getElementById(modalId);
                if (modal) {
                    modal.style.display = 'block';
                    modal.classList.add('show');
                    document.body.style.overflow = 'hidden';
                }
            }
            
            function hideModal(modalId) {
                const modal = document.getElementById(modalId);
                if (modal) {
                    modal.style.display = 'none';
                    modal.classList.remove('show');
                    document.body.style.overflow = 'auto';
                }
            }
            
            // 点击模态框背景关闭
            document.addEventListener('click', function(e) {
                if (e.target.classList.contains('modal')) {
                    hideModal(e.target.id);
                }
            });
        </script>
        
        <script>
            let currentZipId = null;
            
            // 简化的代码高亮
            function highlightCode(code) {
                // 基本的语法高亮（简化版）
                return code
                    .replace(/(\b(?:function|var|let|const|if|else|for|while|return|class|import|export)\b)/g, '<span style="color: #0066cc; font-weight: bold;">$1</span>')
                    .replace(/(['"]).+?\1/g, '<span style="color: #009900;">$&</span>')
                    .replace(/(\d+)/g, '<span style="color: #ff6600;">$1</span>')
                    .replace(/(\/\/.*$)/gm, '<span style="color: #999999; font-style: italic;">$1</span>');
            }
            
            // 页面加载完成后初始化
            document.addEventListener('DOMContentLoaded', function() {
                console.log('=== 页面加载完成，开始初始化 ===');
                
                // 测试关键元素是否存在
                const uploadButton = document.querySelector('button[onclick*="zipFileInput"]');
                const fileInput = document.getElementById('zipFileInput');
                const uploadSection = document.getElementById('uploadSection');
                
                console.log('上传按钮:', uploadButton);
                console.log('文件输入框:', fileInput);
                console.log('上传区域:', uploadSection);
                
                // 验证函数是否定义
                console.log('handleFileSelect函数:', typeof handleFileSelect);
                console.log('uploadFile函数:', typeof uploadFile);
                
                refreshZipList();
            });

            // 刷新ZIP列表
            async function refreshZipList() {
                try {
                    const response = await fetch('/api/zip/list');
                    const zipList = await response.json();
                    displayZipList(zipList);
                } catch (error) {
                    console.error('获取ZIP列表失败:', error);
                    document.getElementById('zipList').innerHTML = 
                        '<div class="alert alert-danger">加载ZIP列表失败</div>';
                }
            }

            // 显示ZIP列表
            function displayZipList(zipList) {
                const container = document.getElementById('zipList');
                
                if (zipList.length === 0) {
                    container.innerHTML = '<div class="alert alert-info">没有找到ZIP文件</div>';
                    return;
                }

                const html = zipList.map(zip => `
                    <div class="card zip-card mb-3" onclick="selectZip(${zip.id})">
                        <div class="card-body">
                            <div class="d-flex justify-content-between align-items-start">
                                <div class="flex-grow-1">
                                    <h6 class="card-title mb-2">${zip.zip_name}</h6>
                                    <p class="card-text small text-muted mb-2">${zip.zip_file}</p>
                                    <div class="small text-muted">
                                        <div>📁 ${zip.file_count} 个文件</div>
                                        <div>📦 大小: ${formatFileSize(zip.file_size || 0)}</div>
                                        <div>🕒 创建: ${zip.created_time || '未知'}</div>
                                        <div>✏️ 修改: ${zip.modified_time || '未知'}</div>
                                    </div>
                                </div>
                                <div class="text-end">
                                    <span class="badge ${zip.status === 'success' ? 'bg-success' : 'bg-danger'}">
                                        ${zip.status === 'success' ? '✓ 成功' : '✗ 失败'}
                                    </span>
                                    <div class="btn-group-vertical mt-2">
                                        <button class="btn btn-sm btn-outline-primary" onclick="event.stopPropagation(); copyZipInfo('${zip.zip_name}', '${zip.created_time}', '${zip.modified_time}', ${zip.file_count}, ${zip.file_size})">
                                            📋 复制
                                        </button>
                                        ${zip.status === 'failed' ? 
                                            `<button class="btn btn-warning btn-sm" onclick="event.stopPropagation(); reprocessZip(${zip.id})">
                                                🔄 重新处理
                                            </button>` : ''}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                `).join('');
                
                container.innerHTML = html;
            }

            // 选择ZIP包
            async function selectZip(zipId) {
                currentZipId = zipId;
                
                // 高亮选中的ZIP卡片
                document.querySelectorAll('.zip-card').forEach(card => {
                    card.classList.remove('border-primary');
                });
                event.currentTarget.classList.add('border-primary');
                
                try {
                    const response = await fetch(`/api/zip/${zipId}/files`);
                    const files = await response.json();
                    displayFileList(files);
                } catch (error) {
                    console.error('获取文件列表失败:', error);
                    document.getElementById('fileList').innerHTML = 
                        '<div class="alert alert-danger">加载文件列表失败</div>';
                }
            }

            // 显示文件列表
            function displayFileList(files) {
                const container = document.getElementById('fileList');
                
                // 保存当前文件列表到全局变量
                window.currentFiles = files;
                
                // 调试：输出文件信息到控制台
                console.log('文件列表数据:', files);
                
                if (files.length === 0) {
                    container.innerHTML = '<p class="text-muted text-center mt-5">没有找到文件</p>';
                    return;
                }

                const html = files.map(file => {
                    const icon = getFileIcon(file.type);
                    const size = formatFileSize(file.size);
                    
                    // 处理时间显示
                    const createdTime = file.created_time || '获取中...';
                    const modifiedTime = file.modified_time || '获取中...';
                    
                    // 检查是否为图片文件
                    const isImage = isImageFile(file.name);
                    
                    return `
                        <div class="file-item border-bottom py-3" style="cursor: pointer;" onclick="viewFile('${file.path}')">
                            <div class="d-flex justify-content-between align-items-start">
                                <div class="flex-grow-1">
                                    <div class="d-flex align-items-center mb-1">
                                        <span class="file-icon ${file.type}-icon me-2">${icon}</span>
                                        <span class="fw-bold text-primary" style="cursor: pointer;">${file.name}</span>
                                        ${isImage ? '<span class="badge bg-success ms-2">🖼️ 图片</span>' : ''}
                                    </div>
                                    <div class="small text-muted">
                                        <div>📁 大小: ${size}</div>
                                        <div>🕒 创建: ${createdTime}</div>
                                        <div>✏️ 修改: ${modifiedTime}</div>
                                    </div>
                                </div>
                                <div class="text-end">
                                    <div class="btn-group-vertical">
                                        <button class="btn btn-sm btn-outline-primary mb-1" onclick="event.stopPropagation(); viewFile('${file.path}')">
                                            👁️ 查看
                                        </button>
                                        ${isImage ? `
                                        <button class="btn btn-sm btn-outline-success" onclick="event.stopPropagation(); viewImageInModal('${file.path}', '${file.name}')">
                                            🖼️ 图片
                                        </button>
                                        ` : ''}
                                    </div>
                                </div>
                            </div>
                        </div>
                    `;
                }).join('');
                
                container.innerHTML = html;
            }

            // 查看文件内容
            async function viewFile(filePath) {
                try {
                    // 保存当前文件路径，用于在displayFileContent中获取文件信息
                    window.currentFilePath = filePath;
                    
                    const fileName = filePath.split('/').pop();
                    
                    // 检查是否为图片文件
                    if (isImageFile(fileName)) {
                        // 直接显示图片
                        try {
                            const response = await fetch(`/api/documents/image/${encodeURIComponent(fileName)}`);
                            if (!response.ok) {
                                throw new Error('无法加载图片');
                            }
                            
                            const blob = await response.blob();
                            const reader = new FileReader();
                            reader.onload = function(e) {
                                const imageUrl = e.target.result;
                                const container = document.getElementById('contentViewer');
                                container.innerHTML = `
                                    <div class="text-center">
                                        <div class="d-flex justify-content-between align-items-center mb-3">
                                            <h5>🖼️ ${fileName}</h5>
                                            <div class="btn-group">
                                                <button class="btn btn-sm btn-outline-primary" onclick="copyImageInfo('${fileName}', '${filePath}')">
                                                    📋 复制信息
                                                </button>
                                            </div>
                                        </div>
                                        <div class="mt-3">
                                            <img src="${imageUrl}" alt="${fileName}" 
                                                 class="img-fluid border rounded shadow" 
                                                 style="max-height: 70vh; cursor: pointer;"
                                                 onclick="openImageModal('${imageUrl}', '${fileName}')">
                                        </div>
                                        <div class="alert alert-info mt-3">
                                            <small>
                                                <strong>💡 提示:</strong> 点击图片可放大查看
                                                <br><strong>📂 文件:</strong> ${fileName}
                                                <br><strong>📊 路径:</strong> ${filePath}
                                            </small>
                                        </div>
                                        <div class="mt-2">
                                            <button class="btn btn-success btn-sm" onclick="openImageModal('${imageUrl}', '${fileName}')">
                                                🔍 放大查看
                                            </button>
                                            <button class="btn btn-primary btn-sm ms-2" onclick="downloadImage()">
                                                💾 下载图片
                                            </button>
                                            <button class="btn btn-outline-secondary btn-sm ms-2" onclick="copyImagePath('${filePath}')">
                                                📎 复制路径
                                            </button>
                                        </div>
                                    </div>
                                `;
                                // 保存当前图片信息用于下载
                                window.currentImageData = {
                                    src: imageUrl,
                                    filename: fileName
                                };
                                // 清空文本内容（因为这是图片）
                                window.currentFileContent = '';
                            };
                            reader.readAsDataURL(blob);
                        } catch (error) {
                            console.error('加载图片失败:', error);
                            document.getElementById('contentViewer').innerHTML = 
                                '<div class="alert alert-danger">无法加载图片: ' + error.message + '</div>';
                        }
                    } else {
                        // 处理文本文件
                        const response = await fetch(`/api/file/content?file_path=${encodeURIComponent(filePath)}`);
                        const fileData = await response.json();
                        
                        // 调试信息
                        console.log('获取到的文件数据:', {
                            filename: fileData.filename,
                            file_type: fileData.file_type,
                            contentLength: fileData.content ? fileData.content.length : 0,
                            contentPreview: fileData.content ? fileData.content.substring(0, 100) : 'null'
                        });
                        
                        displayFileContent(fileData);
                    }
                } catch (error) {
                    console.error('获取文件内容失败:', error);
                    let errorMessage = '读取文件失败';
                    if (error.response) {
                        // 服务器返回了错误响应
                        try {
                            const errorData = await error.response.json();
                            errorMessage = errorData.detail || '服务器错误';
                        } catch (parseError) {
                            errorMessage = `服务器错误 (${error.response.status})`;
                        }
                    } else if (error.message) {
                        errorMessage = error.message;
                    }
                    document.getElementById('contentViewer').innerHTML = 
                        `<div class="alert alert-danger">
                            <strong>📄 文件读取失败</strong><br>
                            ${errorMessage}
                            <br><small class="text-muted">请检查文件编码或联系管理员</small>
                        </div>`;
                }
            }

            // 在模态框中查看图片
            async function viewImageInModal(filePath, fileName) {
                try {
                    // 使用文档API获取图片
                    const imagePath = filePath.split('/').pop(); // 获取文件名
                    const response = await fetch(`/api/documents/image/${encodeURIComponent(imagePath)}`);
                    
                    if (!response.ok) {
                        throw new Error('无法加载图片');
                    }
                    
                    const blob = await response.blob();
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        openImageModal(e.target.result, fileName);
                    };
                    reader.readAsDataURL(blob);
                } catch (error) {
                    console.error('加载图片失败:', error);
                    alert('无法加载图片: ' + error.message);
                }
            }

            // 显示文件内容
            function displayFileContent(fileData) {
                const container = document.getElementById('contentViewer');
                
                // 获取当前选中的文件信息
                const currentFiles = window.currentFiles || [];
                const currentFile = currentFiles.find(f => f.path === window.currentFilePath);
                
                // 存储当前文件内容用于复制功能
                window.currentFileContent = fileData.content || '';
                
                // 调试信息
                console.log('存储的文件内容信息:', {
                    filename: fileData.filename,
                    contentLength: window.currentFileContent.length,
                    contentType: typeof window.currentFileContent,
                    isEmpty: !window.currentFileContent,
                    contentStart: window.currentFileContent.substring(0, 50)
                });
                
                let html = `
                    <div class="file-header mb-3 p-3 bg-light rounded">
                        <div class="d-flex justify-content-between align-items-start">
                            <div>
                                <h6 class="mb-2">📄 ${fileData.filename}</h6>
                                <div class="small text-muted">
                                    <div>📝 类型: ${fileData.file_type ? fileData.file_type.toUpperCase() : '未知'}</div>
                                    ${currentFile ? `
                                        <div>📁 大小: ${formatFileSize(currentFile.size)}</div>
                                        <div>🕒 创建时间: ${currentFile.created_time || '未知'}</div>
                                        <div>✏️ 修改时间: ${currentFile.modified_time || '未知'}</div>
                                    ` : ''}
                                </div>
                            </div>
                            <div class="btn-group">
                                ${fileData.content ? `
                                <button class="btn btn-sm btn-outline-primary" onclick="copyCurrentFileContent('${fileData.filename}')">
                                    📋 复制内容
                                </button>
                                ` : ''}
                                <button class="btn btn-sm btn-outline-success" onclick="copyFileInfo('${fileData.filename}', '${fileData.file_type}', '${currentFile?.size || 0}', '${currentFile?.created_time || ''}', '${currentFile?.modified_time || ''}')">
                                    📝 复制信息
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="file-content">
                `;
                
                // 判断文件类型并显示相应内容
                if (fileData.is_image && fileData.image_data) {
                    // 显示图片
                    html += `
                        <div class="text-center mb-3">
                            <img src="${fileData.image_data}" 
                                 alt="${fileData.filename}" 
                                 class="img-fluid border rounded shadow"
                                 style="max-width: 100%; max-height: 600px; cursor: pointer;"
                                 onclick="openImageModal('${fileData.image_data}', '${fileData.filename}')">
                        </div>
                        <div class="alert alert-info">
                            <small>
                                <strong>💡 提示:</strong> 点击图片可放大查看
                                <br><strong>🖼️ 格式:</strong> ${fileData.file_extension?.toUpperCase()}
                                <br><strong>📊 MIME:</strong> ${fileData.mime_type}
                            </small>
                        </div>
                    `;
                } else if (fileData.file_type === 'markdown' && fileData.content) {
                    // Markdown渲染
                    html += parseMarkdown(fileData.content);
                } else if (fileData.content) {
                    // 代码高亮
                    const highlightedCode = highlightCode(fileData.content);
                    html += `<pre><code>${highlightedCode}</code></pre>`;
                } else if (fileData.message) {
                    // 显示消息
                    html += `<div class="alert alert-warning">${fileData.message}</div>`;
                }
                
                html += '</div>';
                container.innerHTML = html;
            }

            // 重新处理ZIP包
            async function reprocessZip(zipId) {
                try {
                    const response = await fetch(`/api/zip/${zipId}/reprocess`, {
                        method: 'POST'
                    });
                    const result = await response.json();
                    
                    if (result.status === 'success') {
                        alert('重新处理成功！');
                        refreshZipList();
                    } else {
                        alert('重新处理失败！');
                    }
                } catch (error) {
                    console.error('重新处理失败:', error);
                    alert('重新处理失败！');
                }
            }

            // 清空查看器
            function clearViewer() {
                document.getElementById('contentViewer').innerHTML = 
                    '<p class="text-muted text-center mt-5">请选择一个文件查看内容</p>';
            }

            // 获取文件图标
            function getFileIcon(type) {
                switch(type) {
                    case 'md': return '📝';
                    case 'txt': return '📄';
                    case 'py': return '🐍';
                    case 'js': return '📜';
                    case 'html': return '🌐';
                    case 'css': return '🎨';
                    case 'jpg':
                    case 'jpeg':
                    case 'png':
                    case 'gif':
                    case 'bmp':
                    case 'webp':
                    case 'svg': return '🖼️';
                    case 'pdf': return '📕';
                    case 'zip':
                    case 'rar':
                    case '7z': return '🗜️';
                    default: return '📋';
                }
            }

            // 格式化文件大小
            function formatFileSize(bytes) {
                if (bytes === 0) return '0 B';
                const k = 1024;
                const sizes = ['B', 'KB', 'MB', 'GB'];
                const i = Math.floor(Math.log(bytes) / Math.log(k));
                return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
            }

            // 打开图片放大查看模态框
            function openImageModal(imageSrc, filename) {
                const modalImage = document.getElementById('modalImage');
                const modalTitle = document.getElementById('imageModalLabel');
                
                modalImage.src = imageSrc;
                modalImage.alt = filename;
                modalTitle.textContent = `🖼️ ${filename}`;
                
                // 保存当前图片信息用于下载
                window.currentImageData = {
                    src: imageSrc,
                    filename: filename
                };
                
                showModal('imageModal');
            }

            // 下载图片
            function downloadImage() {
                if (!window.currentImageData) return;
                
                const link = document.createElement('a');
                link.href = window.currentImageData.src;
                link.download = window.currentImageData.filename;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }

            // 检测文件是否为图片
            function isImageFile(filename) {
                const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
                const extension = filename.split('.').pop().toLowerCase();
                return imageExtensions.includes(extension);
            }

            // 复制当前文件内容到剪贴板（使用全局变量）
            async function copyCurrentFileContent(filename) {
                try {
                    const content = window.currentFileContent || '';
                    if (!content) {
                        showCopyNotification(`文件 "${filename}" 没有可复制的内容`);
                        return;
                    }
                    
                    console.log('准备复制的内容长度:', content.length);
                    console.log('内容预览:', content.substring(0, 100) + (content.length > 100 ? '...' : ''));
                    
                    await navigator.clipboard.writeText(content);
                    showCopyNotification(`已复制 "${filename}" 的内容到剪贴板！(${content.length} 个字符)`);
                } catch (err) {
                    console.error('复制失败:', err);
                    // 兜底方案
                    try {
                        const content = window.currentFileContent || '';
                        const textArea = document.createElement('textarea');
                        textArea.value = content;
                        textArea.style.position = 'fixed';
                        textArea.style.left = '-999999px';
                        textArea.style.top = '-999999px';
                        document.body.appendChild(textArea);
                        textArea.focus();
                        textArea.select();
                        document.execCommand('copy');
                        document.body.removeChild(textArea);
                        showCopyNotification(`已复制 "${filename}" 的内容到剪贴板！(${content.length} 个字符)`);
                    } catch (fallbackErr) {
                        console.error('兜底方案也失败:', fallbackErr);
                        showCopyNotification(`复制失败: ${fallbackErr.message}`);
                    }
                }
            }

            // 复制文件内容到剪贴板
            async function copyFileContent(filename, content) {
                try {
                    await navigator.clipboard.writeText(content);
                    showCopyNotification(`已复制 "${filename}" 的内容到剪贴板！`);
                } catch (err) {
                    // 兜底方案
                    const textArea = document.createElement('textarea');
                    textArea.value = content;
                    document.body.appendChild(textArea);
                    textArea.select();
                    document.execCommand('copy');
                    document.body.removeChild(textArea);
                    showCopyNotification(`已复制 "${filename}" 的内容到剪贴板！`);
                }
            }

            // 复制文件信息到剪贴板
            async function copyFileInfo(filename, fileType, size, createdTime, modifiedTime) {
                const fileInfo = `文件名: ${filename}
文件类型: ${fileType ? fileType.toUpperCase() : '未知'}
文件大小: ${formatFileSize(parseInt(size) || 0)}
创建时间: ${createdTime || '未知'}
修改时间: ${modifiedTime || '未知'}`;
                
                try {
                    await navigator.clipboard.writeText(fileInfo);
                    showCopyNotification(`已复制 "${filename}" 的信息到剪贴板！`);
                } catch (err) {
                    // 兜底方案
                    const textArea = document.createElement('textarea');
                    textArea.value = fileInfo;
                    document.body.appendChild(textArea);
                    textArea.select();
                    document.execCommand('copy');
                    document.body.removeChild(textArea);
                    showCopyNotification(`已复制 "${filename}" 的信息到剪贴板！`);
                }
            }

            // 显示复制成功通知
            function showCopyNotification(message) {
                // 创建通知元素
                const notification = document.createElement('div');
                notification.className = 'alert alert-success position-fixed';
                notification.style.cssText = `
                    top: 20px;
                    right: 20px;
                    z-index: 9999;
                    min-width: 300px;
                    animation: slideInRight 0.3s ease-out;
                `;
                notification.innerHTML = `
                    <div class="d-flex align-items-center">
                        <span class="me-2">✅</span>
                        <span>${message}</span>
                        <button type="button" class="close" onclick="this.parentElement.parentElement.remove()" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                `;
                
                // 添加CSS动画
                if (!document.getElementById('copy-notification-style')) {
                    const style = document.createElement('style');
                    style.id = 'copy-notification-style';
                    style.textContent = `
                        @keyframes slideInRight {
                            from { transform: translateX(100%); opacity: 0; }
                            to { transform: translateX(0); opacity: 1; }
                        }
                        @keyframes slideOutRight {
                            from { transform: translateX(0); opacity: 1; }
                            to { transform: translateX(100%); opacity: 0; }
                        }
                    `;
                    document.head.appendChild(style);
                }
                
                document.body.appendChild(notification);
                
                // 3秒后自动消失
                setTimeout(() => {
                    notification.style.animation = 'slideOutRight 0.3s ease-in';
                    setTimeout(() => {
                        if (notification.parentElement) {
                            notification.remove();
                        }
                    }, 300);
                }, 3000);
            }

            // 复制图片信息
            async function copyImageInfo(fileName, filePath) {
                const imageInfo = `图片文件信息
文件名: ${fileName}
文件路径: ${filePath}
文件类型: 图片文件
查看时间: ${new Date().toLocaleString()}`;
                
                try {
                    await navigator.clipboard.writeText(imageInfo);
                    showCopyNotification(`已复制图片 "${fileName}" 的信息到剪贴板！`);
                } catch (err) {
                    // 兜底方案
                    const textArea = document.createElement('textarea');
                    textArea.value = imageInfo;
                    document.body.appendChild(textArea);
                    textArea.select();
                    document.execCommand('copy');
                    document.body.removeChild(textArea);
                    showCopyNotification(`已复制图片 "${fileName}" 的信息到剪贴板！`);
                }
            }

            // 复制图片路径
            async function copyImagePath(filePath) {
                try {
                    await navigator.clipboard.writeText(filePath);
                    showCopyNotification(`已复制图片路径到剪贴板！`);
                } catch (err) {
                    // 兜底方案
                    const textArea = document.createElement('textarea');
                    textArea.value = filePath;
                    document.body.appendChild(textArea);
                    textArea.select();
                    document.execCommand('copy');
                    document.body.removeChild(textArea);
                    showCopyNotification(`已复制图片路径到剪贴板！`);
                }
            }

            // 复制ZIP包信息
            async function copyZipInfo(zipName, createdTime, modifiedTime, fileCount, fileSize) {
                const zipInfo = `ZIP包信息
文件名: ${zipName}
创建时间: ${createdTime || '未知'}
修改时间: ${modifiedTime || '未知'}
文件数量: ${fileCount} 个
文件大小: ${formatFileSize(fileSize || 0)}
查看时间: ${new Date().toLocaleString()}`;
                
                try {
                    await navigator.clipboard.writeText(zipInfo);
                    showCopyNotification(`已复制ZIP包 "${zipName}" 的信息到剪贴板！`);
                } catch (err) {
                    // 兜底方案
                    const textArea = document.createElement('textarea');
                    textArea.value = zipInfo;
                    document.body.appendChild(textArea);
                    textArea.select();
                    document.execCommand('copy');
                    document.body.removeChild(textArea);
                    showCopyNotification(`已复制ZIP包 "${zipName}" 的信息到剪贴板！`);
                }
            }
        </script>
    </body>
    </html>
    """
    return html_content
